<template>
  <div class="project-management-container">
    <!-- 搜索区域：仅管理员和审核员可见 -->
    <el-card v-if="!isTeacher" class="search-card">
      <div class="search-header">
        <h2>科研项目管理</h2>
        <el-button type="primary" @click="handleAddProject">添加项目</el-button>
      </div>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="教师姓名">
          <el-input v-model="searchForm.teacherName" placeholder="请输入教师姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-input v-model="searchForm.department" placeholder="请输入所属部门" clearable></el-input>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.name" placeholder="请输入项目名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="项目类型">
          <el-select v-model="searchForm.type" placeholder="请选择项目类型" clearable style="width: 120px;">
            <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经费范围">
          <el-input-number v-model="searchForm.fundingMin" placeholder="最小金额" :min="0" :precision="2" style="width: 120px;"></el-input-number>
          <span class="range-separator">-</span>
          <el-input-number v-model="searchForm.fundingMax" placeholder="最大金额" :min="0" :precision="2" style="width: 120px;"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 教师视图：简化的头部 -->
    <el-card v-if="isTeacher" class="search-card">
      <div class="search-header">
        <h2>我的科研项目</h2>
        <el-button type="primary" @click="handleAddProject">添加项目</el-button>
      </div>
    </el-card>

    <!-- 项目列表 -->
    <el-card class="list-card">
      <el-table 
        :data="projectList" 
        style="width: 100%" 
        v-loading="loading" 
        border
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="teacherName" label="教师姓名" min-width="100" v-if="!isTeacher"></el-table-column>
        <el-table-column prop="departmentName" label="所属部门" min-width="120" v-if="!isTeacher"></el-table-column>
        <el-table-column prop="name" label="项目名称" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="type" label="项目类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getProjectTypeTag(scope.row.type)">{{ getProjectTypeText(scope.row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="funding" label="经费(万元)" width="120" align="center"></el-table-column>
        <el-table-column label="项目周期" width="200" align="center">
          <template #default="scope">
            {{ scope.row.startDate }} 至 {{ scope.row.endDate }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEditProject(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteProject(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑项目对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加科研项目' : '编辑科研项目'" 
      v-model="dialogVisible" 
      width="600px"
    >
      <el-form 
        :model="projectForm" 
        :rules="projectFormRules" 
        ref="projectFormRef" 
        label-width="100px"
      >
        <el-form-item label="教师" prop="teacherId" v-if="!isTeacher">
          <el-select v-model="projectForm.teacherId" placeholder="请选择教师" filterable style="width: 100%">
            <el-option 
              v-for="teacher in teacherOptions" 
              :key="teacher.id" 
              :label="teacher.realName + ' (' + teacher.department + ')'" 
              :value="teacher.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="projectForm.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="项目类型" prop="type">
          <el-select v-model="projectForm.type" placeholder="请选择项目类型" style="width: 100%">
            <el-option v-for="item in projectTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经费(万元)" prop="funding">
          <el-input-number v-model="projectForm.funding" :min="0" :precision="2" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="projectForm.startDate" type="date" placeholder="选择开始日期" style="width: 100%" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="projectForm.endDate" type="date" placeholder="选择结束日期" style="width: 100%" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
        <el-select 
        v-model="projectForm.status" 
        placeholder="请选择状态" 
        style="width: 100%"
        :disabled="isTeacher">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <div v-if="isTeacher" class="status-note">
        <small>注：教师提交的项目默认为待审核状态</small>
        </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProjectForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../stores/user'

// 获取用户信息
const userStore = useUserStore()
const userRole = computed(() => userStore.userRole || localStorage.getItem('userRole'))
const isTeacher = computed(() => userRole.value === 'teacher')
const currentTeacherId = ref(null)

// 项目类型选项
// 修改项目类型选项
const projectTypeOptions = [
{ value: 'national', label: '国家级' },
{ value: 'provincial', label: '省级' },
{ value: 'horizontal', label: '横向' }
]

// 修改获取项目类型文本的函数
const getProjectTypeText = (type) => {
const typeMap = {
'national': '国家级',
'provincial': '省级',
'horizontal': '横向'
}
return typeMap[type] || type
}

// 状态选项
const statusOptions = [
  { value: 'pending', label: '待审核' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已拒绝' }
]

// 获取项目类型标签
const getProjectTypeTag = (type) => {
  const typeMap = {
    'national': 'danger',
    'provincial': 'warning',
    'municipal': 'success',
    'horizontal': 'info'
  }
  return typeMap[type] || 'info'
}


// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 搜索表单
const searchForm = reactive({
  teacherName: '',
  department: '',
  name: '',
  type: '',
  fundingMin: '',
  fundingMax: '',
  status: ''
})

// 项目列表数据
const projectList = ref([])
const loading = ref(false)

// 教师选项
const teacherOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const projectFormRef = ref(null)
const submitLoading = ref(false)

// 项目表单
const projectForm = reactive({
  id: null,
  teacherId: '',
  name: '',
  type: '',
  funding: '',
  startDate: '',
  endDate: '',
  status: 'pending'
})

// 项目表单验证规则
const projectFormRules = {
  teacherId: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择项目类型', trigger: 'change' }
  ],
  funding: [
    { required: true, message: '请输入经费金额', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取当前教师ID
const fetchCurrentTeacherId = async () => {
  if (isTeacher.value) {
    try {
      // 从localStorage获取user并解析JSON
      let userId = userStore.userId
      if (!userId) {
        const userStr = localStorage.getItem('user')
        if (userStr) {
          try {
            const userObj = JSON.parse(userStr)
            userId = userObj.id
          } catch (e) {
            console.error('解析用户信息错误:', e)
          }
        }
      }
      
      if (userId) {
        const response = await axios.get(`http://localhost:8081/api/teacher/getByUserId?userId=${userId}`)
        if (response.data.code === 200 && response.data.data) {
          // 从返回的数据中获取教师ID
          currentTeacherId.value = response.data.data.teacher.id
        }
      } else {
        console.error('未找到用户ID')
      }
    } catch (error) {
      console.error('获取当前教师ID错误:', error)
    }
  }
}

// 获取项目列表
const fetchProjectList = async () => {
  loading.value = true
  try {
    const params = {}
    
    // 管理员或审核员可以按条件筛选
    if (!isTeacher.value) {
      params.teacherName = searchForm.teacherName
      params.department = searchForm.department
      params.name = searchForm.name
      params.type = searchForm.type
      params.status = searchForm.status
      
      // 添加经费范围参数
      if (searchForm.fundingMin) {
        params.fundingMin = searchForm.fundingMin
      }
      if (searchForm.fundingMax) {
        params.fundingMax = searchForm.fundingMax
      }
    }
    
    const response = await axios.post('http://localhost:8081/api/project/list', params)
    if (response.data.code === 200) {
      // 处理返回的数据结构
      if (response.data.data && Array.isArray(response.data.data)) {
        let allProjects = response.data.data.map(item => ({
          id: item.project.id,
          teacherId: item.project.teacherId,
          teacherName: item.teacherName,
          departmentName: item.departmentName,
          name: item.project.name,
          type: item.project.type,
          funding: item.project.funding,
          startDate: item.project.startDate,
          endDate: item.project.endDate,
          status: item.project.status
        }));
        
        // 如果是教师角色，在前端筛选当前教师的项目
        if (isTeacher.value && currentTeacherId.value) {
          projectList.value = allProjects.filter(project => project.teacherId === currentTeacherId.value);
          console.log('筛选后的项目数量:', projectList.value.length);
        } else {
          projectList.value = allProjects;
        }
      } else {
        projectList.value = [];
      }
    } else {
      ElMessage.error(response.data.msg || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表错误:', error)
    ElMessage.error('获取项目列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 获取教师列表（用于下拉选择）
const fetchTeacherOptions = async () => {
  // 如果是教师角色，不需要获取教师列表
  if (isTeacher.value) return
  
  try {
    const response = await axios.post('http://localhost:8081/api/teacher/list', {})
    if (response.data.code === 200) {
      teacherOptions.value = response.data.data.map(item => ({
        id: item.teacher.id,
        realName: item.user.realName,
        department: item.teacher.department
      }))
    } else {
      ElMessage.error(response.data.msg || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表错误:', error)
    ElMessage.error('获取教师列表失败，请检查网络连接')
  }
}

// 搜索项目
const handleSearch = () => {
  fetchProjectList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchProjectList()
}

// 添加项目
const handleAddProject = () => {
  dialogType.value = 'add'
  resetProjectForm()
  
  dialogVisible.value = true
}

// 编辑项目
const handleEditProject = (row) => {
  dialogType.value = 'edit'
  projectForm.id = row.id
  projectForm.teacherId = row.teacherId
  projectForm.name = row.name
  projectForm.type = row.type
  projectForm.funding = row.funding
  projectForm.startDate = row.startDate
  projectForm.endDate = row.endDate
  projectForm.status = row.status
  
  dialogVisible.value = true
}

// 重置项目表单
const resetProjectForm = () => {
  if (projectFormRef.value) {
    projectFormRef.value.resetFields()
  }
  
  projectForm.id = null
  projectForm.teacherId = ''
  projectForm.name = ''
  projectForm.type = ''
  projectForm.funding = ''
  projectForm.startDate = ''
  projectForm.endDate = ''
  projectForm.status = 'pending'
}

// 提交项目表单
const submitProjectForm = () => {
  // 如果是教师角色，确保使用当前教师ID和待审核状态
  if (isTeacher.value && currentTeacherId.value) {
    projectForm.teacherId = currentTeacherId.value
    projectForm.status = 'pending' // 教师提交的项目始终为待审核状态
  }
  
  projectFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8081/api/project/add' 
          : 'http://localhost:8081/api/project/update'
        
        const response = await axios.post(url, {
          id: projectForm.id,
          teacherId: projectForm.teacherId,
          name: projectForm.name,
          type: projectForm.type,
          funding: projectForm.funding,
          startDate: projectForm.startDate,
          endDate: projectForm.endDate,
          status: projectForm.status
        })
        
        if (response.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加项目成功' : '编辑项目成功')
          dialogVisible.value = false
          fetchProjectList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || (dialogType.value === 'add' ? '添加项目失败' : '编辑项目失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加项目错误:' : '编辑项目错误:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加项目失败，请检查网络连接' : '编辑项目失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除项目
const handleDeleteProject = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目 "${row.name}" 吗？此操作将不可逆！`,
      '删除项目',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const params = new URLSearchParams()
    params.append('id', row.id)
    
    const response = await axios.post('http://localhost:8081/api/project/delete', params)
    
    if (response.data.code === 200) {
      ElMessage.success('删除项目成功')
      fetchProjectList() // 刷新列表
    } else {
      ElMessage.error(response.data.msg || '删除项目失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除项目错误:', error)
      ElMessage.error('删除项目失败，请检查网络连接')
    }
  }
}

// 页面加载时获取数据
onMounted(async () => {
  // 先获取教师ID，再获取项目列表
  if (isTeacher.value) {
    await fetchCurrentTeacherId()
  }
  
  // 获取项目列表
  await fetchProjectList()
  
  // 如果不是教师角色，获取教师选项
  if (!isTeacher.value) {
    await fetchTeacherOptions()
  }
})
</script>

<style scoped>
.project-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-top: 15px;
}

.range-separator {
  margin: 0 8px;
}

.list-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}
</style>